package com.csust.travel.controller;

import cn.hutool.core.util.StrUtil;
import com.csust.travel.Constants.MinioProp;
import com.csust.travel.Constants.ResultCode;
import com.csust.travel.exception.ServiceException;
import com.csust.travel.model.R;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
@RestController
@RequestMapping("/upload")
@CrossOrigin
@Slf4j
public class UploadController {
  @Autowired
  private MinioClient minioClient;
  @Autowired
  private MinioProp minioProp;

  //minio
  @PostMapping("/image")
  public R uploadImage(@RequestParam("file") MultipartFile image) {
    try {
      String fileName = UUID.randomUUID() + "." + StrUtil.subAfter(image.getOriginalFilename(), ".", true);
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
      String path = formatter.format(new Date()).replace('-', '/');
      //上传
      minioClient.putObject(PutObjectArgs.builder()
        .bucket(minioProp.getBucket())
        .object(path + '/' + fileName)
        .contentType(image.getContentType())
        .stream(image.getInputStream(), image.getInputStream().available(), -1)
        .build());
//      qiniuUtils.upload(image, path + '/' + fileName);
      // 返回结果
      log.info("文件上传成功，{}", fileName);
      HashMap<String, String> result = new HashMap<>();
      result.put("name", fileName);
      result.put("url", minioProp.getEndpoint()+ '/'+minioProp.getBucket() +'/'+ path + '/' + fileName);
      System.out.println("112");
      return R.ok(result);
    } catch (Exception e) {
      log.error(e.toString());
      throw new ServiceException(ResultCode.Fail);
    }
  }
}
